/**
 * 云静表格
 */
layui.use(['jquery', 'yunj', 'element', 'elemProgress', 'button', 'tableToolbar', 'table', "validate"], function () {
    let win = window;
    let doc = document;
    let $ = layui.jquery;
    let element = layui.element;
    let elemProgress = layui.elemProgress;
    let button = layui.button;
    let tableToolbar = layui.tableToolbar;
    let table = layui.table;
    let validate = layui.validate;

    class YunjTable {

        constructor(obj) {
            this.version = '1.0.0';                   // 版本号

            this.id = obj.id;                         // 当前对象id

            this.rawEl = obj.elem;                    // 原始元素

            this.rawArgs = obj.args;                  // 原始数据

            this.boxEl = null;                       // 顶部父元素

            this.stateBoxEl = null;                  // 状态栏父元素

            this.filterBoxEl = null;                 // 筛选表单父元素

            this.url = null;                         //请求地址

            this.state = null;                       //当前状态

            this.iframeWidth = null;                 //当前页面iframe宽度，变化时更新

            this.filterFormEl = null;                //筛选表单

            this.filterFields = {};                  // 筛选表单字段实例容器

            this.fieldSort = {};                     // 表格字段排序

            this.table = null;                      //当前表格对象

            this.tableCurrTd = null;                //当前表格操作格子，用于触发工具栏展开绑定事件无效

            this.tableItemCount = 0;                //当前表格数据项数量

            this.tableItems = [];                   //当前表格数据项

            this.elemProgress = null;              // 表格加载进度对象

            this.init();
        }

        init() {
            let that = this;
            if (!that.id || !that.rawArgs || win.yunj.isEmptyObj(that.rawArgs)) return false;
            // 初始化布局
            that.initLayout();
            // 初始化
            that.setDataInit();
            // 进度0
            that.elemProgress = elemProgress({elem: that.boxEl});
            // 渲染
            that.render().then(res => {
                // 设置事件绑定
                that.setEventBind();
                // 进度100%
                that.elemProgress.reset_progress(100);
            });
        }

        /**
         *
         * @param {string} attr
         * @private {bool}
         */
        rawArgsIsSetAttr(attr) {
            return this.rawArgs.hasOwnProperty(attr);
        }

        // 判断是否设置state
        isSetState() {
            return this.rawArgsIsSetAttr("state");
        }

        // 判断是否设置page
        isSetPage() {
            return this.rawArgsIsSetAttr("page");
        }

        // 判断是否设置limit
        isSetLimit() {
            return this.rawArgsIsSetAttr("limit");
        }

        // 判断是否设置limits
        isSetLimits() {
            return this.rawArgsIsSetAttr("limits");
        }

        // 判断是否设置filter
        isSetFilter() {
            return this.rawArgsIsSetAttr("filter");
        }

        // 判断是否设置toolbar
        isSetToolbar() {
            return this.rawArgsIsSetAttr("toolbar");
        }

        // 判断是否设置filter
        isSetDefaultToolbar() {
            return this.rawArgsIsSetAttr("defaultToolbar");
        }

        // 判断是否设置import
        isSetImport() {
            return this.rawArgsIsSetAttr("import");
        }

        // 判断是否设置cols
        isSetCols() {
            return this.rawArgsIsSetAttr("cols");
        }

        // 初始化布局
        initLayout() {
            let that = this;
            let layout = "";
            if (that.isSetState()) layout += `<div class="yunj-table-state-box"></div>`;
            if (that.isSetFilter()) layout += '<div class="yunj-table-filter-box" style="padding-bottom: 0"></div>';
            if (that.isSetCols()) layout += `<div class="yunj-table-lay-table-box" style="padding-top: 0"><table class="layui-table" id="yunj_table_${that.id}" lay-filter="yunj_table_${that.id}"></table></div>`;
            if (that.isSetDefaultToolbar()) layout += '<div class="yunj-table-default-toolbar-box" style="display: none;"></div>';
            layout = `<div class="yunj-table-box" lay-filter="${that.id}">${layout}</div>`;
            that.rawEl.after(layout);
        }

        // 数据初始化
        setDataInit() {
            let that = this;
            let id = that.id;
            let rawArgs = that.rawArgs;
            // 元素
            let boxEl = $(`.yunj-table-box[lay-filter=${id}]`);
            that.boxEl = boxEl;
            if (that.isSetState()) that.stateBoxEl = boxEl.find('.yunj-table-state-box');
            if (that.isSetFilter()) that.filterBoxEl = boxEl.find('.yunj-table-filter-box');
            // url
            that.url = rawArgs.hasOwnProperty('url') ? rawArgs.url : yunj.url(false);
            // 内容区宽度
            that.iframeWidth = $(doc).width();
        }

        // 渲染
        async render() {
            let that = this;
            that.renderState();
            await that.renderFilter();
            await that.renderTable();
            // 渲染完成事件触发
            $(doc).trigger(`yunj_table_${that.id}_render_done`);
            return 'done';
        }

        // 渲染状态栏
        renderState() {
            let that = this;
            if (!that.isSetState()) return;
            that.setStateLayout();
            // 设置当前状态
            that.state = that.stateBoxEl.find('.layui-this').data('state') || null;
        }

        // 设置状态栏布局
        setStateLayout() {
            let that = this;
            if (that.stateBoxEl.find('li').length > 0) return false;
            let states = that.rawArgs.state;
            let layout = '';
            for (let state in states) {
                if (!states.hasOwnProperty(state)) continue;
                layout += `<li data-state="${state}">${states[state]}(<span class="count">0</span>)</li>`;
            }
            layout = `<div class="layui-tab layui-tab-brief state-box" lay-filter="${that.id}_state"><ul class="layui-tab-title">${layout}</ul></div>`;
            that.stateBoxEl.html(layout);
            that.stateBoxEl.find('.layui-tab-title li:first').addClass('layui-this');
        }

        // 渲染筛选表单
        async renderFilter() {
            let that = this;
            if (!that.isSetFilter()) return;
            await that.setFilterForm();

            let filterBoxEl = that.filterBoxEl.find('.filter-form');
            if (filterBoxEl.length <= 0) return;
            filterBoxEl.removeClass('filter-form-this');

            let filterFormEl = that.filterBoxEl.find(`.filter-form[lay-filter=${that.getCurrFilterFormLayFilter()}]`);
            if (filterFormEl.length <= 0) return;
            filterFormEl.addClass('filter-form-this');
            that.filterFormEl = filterFormEl;

            // 设置筛选表单布局（字段label、按钮、展开/收起）
            that.setFilterFormLayout();
        }

        // 设置筛选表单
        async setFilterForm() {
            let that = this;
            if (!yunj.isEmptyObj(that.filterFields)) return 'done';

            let filter = that.rawArgs.filter;
            if (that.isSetState()) {
                for (let state in filter) {
                    if (!filter.hasOwnProperty(state)) continue;
                    let formId = that.generateFilterFormId(state);
                    let formLayFilter = that.generateFilterFormLayFilterByState(state);
                    let fields = filter[state];
                    that.filterBoxEl.append(`<form class="layui-row layui-form layui-form-pane yunj-form filter-form" lay-filter="${formLayFilter}">`);
                    await that.setFilterFormFields(formId, fields);
                }
            } else {
                that.filterBoxEl.append(`<form class="layui-row layui-form layui-form-pane yunj-form filter-form" lay-filter="${that.generateFilterFormLayFilterByState()}">`);
                await that.setFilterFormFields(that.id, filter);
            }
            return 'done';
        }

        // 设置筛选表单字段
        async setFilterFormFields(formId, fields) {
            let that = this;
            let formLayFilter = that.generateFilterFormLayFilterByFormId(formId);
            for (let key in fields) {
                if (!fields.hasOwnProperty(key)) continue;
                let args = fields[key];
                await new Promise((resolve) => {
                    yunj.formField(args.type, {
                        formId: formId,
                        key: key,
                        args: args,
                    }).then(field => {
                        field.render(
                            `.filter-form[lay-filter=${formLayFilter}]`,
                            `<div class="layui-col-xs12 layui-col-sm6 layui-col-md3 filter-form-item-box">__layout__</div>`
                        ).then(res => {
                            that.filterFields[field.id] = field;
                            resolve('done');
                        });
                    });
                });
            }
            let lastItemHtml = `<div class="layui-col-xs12 layui-col-sm6 layui-col-md3 filter-form-item-box"><div class="layui-form-item yunj-form-item"></div></div>`;
            that.filterBoxEl.find(`.filter-form[lay-filter=${formLayFilter}]`).append(lastItemHtml);
            return 'done';
        }

        // 设置筛选表单布局
        setFilterFormLayout() {
            let that = this;
            if (!that.filterFormEl) return;
            let filterFormEl = that.filterFormEl;

            that.setFilterFormFieldLabelLayout();

            that.setFilterFormButtonLayout();

            //判断筛选字段数量是否>2（包含按钮）
            if (filterFormEl.find(".filter-form-item-box").length <= 2) return;

            //适配屏宽
            let otherFormItemEl = filterFormEl.find(".filter-form-item-box:not(:first,:last)");
            if (win.screen.width > 768) {
                //展开其他的filter-form-item-box
                otherFormItemEl.show('fast');
                //隐藏展开、收起按钮
                filterFormEl.removeClass('filter-form-stow').addClass('filter-form-unfold');
            } else {
                //隐藏其他的filter-form-item-box
                otherFormItemEl.hide('fast');
                //显示展开、收起按钮
                filterFormEl.removeClass('filter-form-stow').addClass('filter-form-unfold');
            }
        }

        // 设置筛选表单字段label布局
        setFilterFormFieldLabelLayout() {
            let that = this;
            let labelMaxWidth = 0;
            let formItemEl = that.filterFormEl.find('.yunj-form-item:not(.layui-form-textarea):not(.yunj-form-editor):not(.yunj-form-markdown)');
            formItemEl.each(function () {
                let currLabelWidth = $(this).find('.layui-form-label').outerWidth();
                if (currLabelWidth > labelMaxWidth) labelMaxWidth = currLabelWidth;
            });
            formItemEl.find('.layui-form-label').css('width', labelMaxWidth + 2 + 'px');
        }

        // 设置筛选表单按钮布局
        setFilterFormButtonLayout() {
            let that = this;
            let formItemEl = that.filterFormEl.find('.yunj-form-item:last');
            if (formItemEl.html().length > 0) return;
            let filterFormLayFilter = that.getCurrFilterFormLayFilter();
            let boxFilter = `.filter-form[lay-filter=${filterFormLayFilter}] .yunj-form-item:last`;
            button.search(filterFormLayFilter).render(boxFilter);
            button.reset(filterFormLayFilter).render(boxFilter);
            formItemEl.append(`<button type="button" class="layui-btn layui-btn-sm layui-btn-primary layui-icon filter-form-layout-control"></button>`);
        }

        // 渲染表格
        async renderTable() {
            let that = this;
            await that.setStateCount();
            await that.renderTableHandle();
        }

        // 设置状态数量
        setStateCount() {
            let that = this;

            return new Promise(resolve => {
                if (!that.isSetState()) {
                    resolve();
                    return;
                }
                let requestData = {builderId: that.id, builderAsyncType: 'stateCount'};
                yunj.request(that.url, requestData, "post").then(res => {
                    let states = res.data;
                    if (!yunj.isEmptyObj(states)) {
                        for (let state in states) {
                            if (!states.hasOwnProperty(state)) continue;
                            let stateEl = that.stateBoxEl.find(`.state-box li[data-state=${state}]`);
                            if (stateEl.length > 0) stateEl.find('.count').html(states[state]);
                        }
                    }
                    resolve();
                }).catch(e => {
                    yunj.error(e);
                });

            });
        }

        // 渲染表格处理
        async renderTableHandle() {
            let that = this;
            if (!that.isSetCols()) return;
            let id = that.id;
            let rawArgs = that.rawArgs;
            let filter = that.requestFilter();
            let args = {
                elem: '#' + that.layuiTableId(),
                url: that.url,
                method: 'post',
                where: {builderId: id, builderAsyncType: 'items', filter: filter, sort: that.requestSort()},
                contentType: 'application/json',
                parseData: function (res) {
                    let data = res.data;
                    let items = yunj.isObj(data) && data.hasOwnProperty('items') ? data.items : [];
                    items.map(item => {
                        item.is_export = false;
                        return item;
                    });
                    that.tableItems = items;
                    return {
                        "code": res.errcode,
                        "msg": res.msg,
                        "count": that.tableItemCount,
                        "data": that.tableItems
                    };
                },
                loading: true,
                text: {none: '暂无相关数据'},
                autoSort: false,
                cols: [],
                done: function (res) {
                    table.resize(this.id);
                    // 渲染表格完成事件触发
                    $(doc).trigger(`yunj_table_${that.id}_render_table_done`);
                }
            };

            // page
            if (that.isSetPage()) {
                if (that.isSetState()) {
                    args.page = yunj.isObj(rawArgs.page) && rawArgs.page.hasOwnProperty(that.state) ? rawArgs.page[that.state] : true;
                } else {
                    args.page = yunj.isBool(rawArgs.page) ? rawArgs.page : true;
                }
                // limit
                if (that.isSetLimit()) {
                    if (that.isSetState()) {
                        args.limit = yunj.isObj(rawArgs.limit) && rawArgs.limit.hasOwnProperty(that.state) ? rawArgs.limit[that.state] : 20;
                    } else {
                        args.limit = yunj.isPositiveInt(rawArgs.limit) ? rawArgs.limit : 20;
                    }
                }
                // limits
                if (that.isSetLimits()) {
                    if (that.isSetState()) {
                        args.limits = yunj.isObj(rawArgs.limits) && rawArgs.limits.hasOwnProperty(that.state) ? rawArgs.limits[that.state] : [10, 20, 30, 40, 50, 60, 70, 80, 90];
                    } else {
                        args.limits = yunj.isPositiveIntArray(rawArgs.limits) ? rawArgs.limits : [10, 20, 30, 40, 50, 60, 70, 80, 90];
                    }
                }
            }

            if (!yunj.isEmptyObj(that.fieldSort)) {
                let field = Object.keys(that.fieldSort)[0];
                args.initSort = {field: field, type: that.fieldSort[field]}
            }

            // 表格头部工具栏
            await that.setTableToolbarArgs(args);

            // 表格头部右侧工具栏
            that.setTableDefaultToolbarArgs(args);

            // 表头
            await that.setTableColsArgs(args);

            // 数据量
            await that.setTableItemCount(filter);

            console.log(args);

            that.table = table.render(args);
        }

        // 设置表格头部工具栏参数
        async setTableToolbarArgs(args) {
            let that = this;
            if (!that.isSetToolbar()) return;
            let id = that.id;
            let rawArgs = that.rawArgs;

            let tableToolbarOptions = {
                tableId: id,
                key: 'toolbar',
            };
            if (that.isSetState()) {
                if (!rawArgs.toolbar.hasOwnProperty(that.state)) return;
                tableToolbarOptions.state = that.state;
                tableToolbarOptions.options = rawArgs.toolbar[that.state];
            } else {
                tableToolbarOptions.options = rawArgs.toolbar;
            }
            await new Promise(resolve => {
                tableToolbar(tableToolbarOptions).render().then(obj => {
                    args.toolbar = `#${obj.id}`;
                    resolve();
                });
            });
        }

        // 设置表格头部右侧工具栏参数
        setTableDefaultToolbarArgs(args) {
            let that = this;
            if (!that.isSetDefaultToolbar()) return;
            let rawArgs = that.rawArgs;

            let defaultToolbar = [];
            let rawDefaultToolbar = [];
            if (that.isSetState()) {
                if (!rawArgs.defaultToolbar.hasOwnProperty(that.state)) return;
                rawDefaultToolbar = rawArgs.defaultToolbar[that.state];
            } else {
                rawDefaultToolbar = rawArgs.defaultToolbar;
            }

            for (let i = 0, len = rawDefaultToolbar.length; i < len; i++) {
                if (rawDefaultToolbar[i] === 'filter' || rawDefaultToolbar[i] === 'print') {
                    defaultToolbar.push(rawDefaultToolbar[i]);
                } else if (rawDefaultToolbar[i] === 'export') {
                    defaultToolbar.push({title: '数据导出', layEvent: 'export', icon: 'layui-icon-export'});
                } else if (rawDefaultToolbar[i] === 'import' && rawArgs.hasOwnProperty("import")) {
                    defaultToolbar.push({title: '数据导入', layEvent: 'import', icon: 'layui-icon-upload'});
                }
            }
            if (rawDefaultToolbar.indexOf("import") === -1 && rawArgs.hasOwnProperty('import')) {
                defaultToolbar.push({title: '数据导入', layEvent: 'import', icon: 'layui-icon-upload'});
            }

            if (defaultToolbar.length > 0) {
                args.toolbar = args.hasOwnProperty('toolbar') ? args.toolbar : true;
                args.defaultToolbar = defaultToolbar;
            }
        }

        // 设置表格表头参数
        async setTableColsArgs(args) {
            let that = this;
            if (!that.isSetCols()) return;

            let id = that.id;
            let rawArgs = that.rawArgs;
            let cols = [];
            let rawCols = [];
            if (that.isSetState()) {
                if (!rawArgs.cols.hasOwnProperty(that.state)) return;
                rawCols = rawArgs.cols[that.state];
            } else {
                rawCols = rawArgs.cols;
            }

            for (let k in rawCols) {
                if (!rawCols.hasOwnProperty(k)) continue;
                let rawCol = rawCols[k];
                let col = yunj.objSupp(rawCol, {
                    field: '',
                    title: '',
                    type: 'normal',
                    align: 'left',
                    sort: false,
                    fixed: false,
                    hide: false,
                    templet: '',
                });
                // 处理hide
                switch (rawCol.hide) {
                    case 'yes':
                        col.hide = true;
                        break;
                    case 'mobileHide':
                        col.hide = yunj.isMobile();
                        break;
                    default:
                        col.hide = false;
                }
                // 处理templet
                let rawTemplet = rawCol['templet'];
                if (rawTemplet.length > 0) {
                    let templetArgs = {
                        tableId: id,
                        key: rawCol.field,
                        args: rawCol,
                    };
                    if (that.isSetState()) templetArgs.state = that.state;

                    await new Promise(resolve => {
                        yunj.tableCol(rawTemplet, templetArgs).then(colObj => {
                            colObj.render().then(res => {
                                col['templet'] = `#${colObj.id}`;
                                resolve();
                            });
                        });
                    });
                }

                if (rawTemplet === 'action') col.minWidth = 80;
                cols.push(col);
            }
            args.cols = [cols];
        }

        // 设置当前条件下的表格数据量
        setTableItemCount(filter = null) {
            let that = this;
            filter = filter || that.requestFilter();
            return new Promise(resolve => {
                yunj.request(that.url, {
                    builderId: that.id,
                    builderAsyncType: 'count',
                    filter: filter
                }, "post").then(res => {
                    let count = res.data.count;
                    that.tableItemCount = yunj.isPositiveInteger(count) ? count : 0;
                    resolve();
                }).catch(e => {
                    yunj.error(e);
                });
            });
        }

        /**
         * 重载表格数据
         * @param {boolean} isFirstPage [是否从第一页开始]
         */
        reloadTableHandle(isFirstPage = true) {
            let that = this;
            let args = {where: {id: that.id, type: 'items', filter: that.requestFilter(), sort: that.requestSort()}};
            if (isFirstPage) args.page = {curr: 1};
            that.table.reload(args);
        }

        // 设置事件绑定
        setEventBind() {
            let that = this;
            let id = that.id;
            let layID = that.layuiTableId();
            // 文档页面宽度发生变化时触发
            $(doc).resize(function () {
                let currIframeWidth = $(doc).width();
                let lastIframeWidth = that.iframeWidth;
                if (currIframeWidth !== lastIframeWidth) {
                    that.iframeWidth = currIframeWidth;
                    that.setFilterFormLayout();
                }
            });
            // 当前展开格子
            $(doc).off('mousedown', `.yunj-table-lay-table-box div[lay-id=${layID}] .layui-table-grid-down`).on('mousedown', `.yunj-table-lay-table-box div[lay-id=${layID}] .layui-table-grid-down`, function () {
                that.tableCurrTd = $(this).closest('td');
            });
            // 展开格子事件
            $(doc).off('click', `.layui-table-tips-main .layui-btn-container[yunj-id=${id}] [lay-event]`).on('click', `.layui-table-tips-main .layui-btn-container[yunj-id=${id}] [lay-event]`, function () {
                if (!that.tableCurrTd) return;
                let el = $(this);
                let layEvent = el.attr('lay-event');
                let layerIdx = el.closest('.layui-table-tips').attr('times');
                layer.close(layerIdx);
                that.tableCurrTd.find(`[lay-event=${layEvent}]`).first().click();
            });
            // 切换状态选项卡
            if (that.isSetState()) {
                element.on(`tab(${id}_state)`, function (data) {
                    let state = $(this).data('state');
                    let lastState = that.state;
                    if (state === lastState) return false;
                    that.stateTabChange().then();
                });
            }
            // 监听筛选表单事件
            if (that.isSetFilter()) {
                // 展开/收起
                that.filterBoxEl.on('click', '.filter-form-layout-control', function () {
                    if (that.filterFormEl.hasClass('filter-form-unfold')) {
                        //转换为收起
                        that.filterFormEl.removeClass('filter-form-unfold').addClass('filter-form-stow');
                    } else {
                        //转换为展开
                        that.filterFormEl.removeClass('filter-form-stow').addClass('filter-form-unfold');
                    }
                    that.filterFormEl.find(".filter-form-item-box:not(:first,:last)").slideToggle("fast");
                });
                // 重置
                that.filterBoxEl.on('click', '.yunj-btn-reset', function () {
                    $(doc).trigger(`yunj_form_${that.getCurrFilterFormId()}_clear`);
                });
                // 搜索
                that.filterBoxEl.on('click', '.yunj-btn-search', function () {
                    that.renderTableHandle().then();
                });
            }
            // 监听工具栏事件
            if (that.isSetToolbar() || that.isSetDefaultToolbar()) {
                table.on(`toolbar(yunj_table_${id})`, function (obj) {
                    let el = $(this);
                    let args = el.data('args');
                    switch (obj.event) {
                        case 'openPopup':
                            let popupUrl = yunj.urlPushParam(args.url, {
                                rawTable: that.id,
                            });
                            yunj.openPopup(popupUrl, args.title, true);
                            break;
                        case 'openTab':
                            let tabUrl = yunj.urlPushParam(args.url, {
                                rawTable: that.id,
                            });
                            yunj.openTab(tabUrl, args.title, true);
                            break;
                        case 'asyncEvent':
                            args.ids = table.checkStatus(obj.config.id).data.map(row => {
                                return row.id
                            });
                            that.asyncEventRequest(args);
                            break;
                        case 'export':
                            yunj.tableExport(that);
                            break;
                        case 'import':
                            let importUrl = that.rawArgs.import[that.state];
                            importUrl = yunj.urlPushParam(importUrl, {
                                rawTable: that.id,
                            });
                            yunj.openPopup(importUrl, '数据导入', true);
                            break;
                    }
                });
            }

            if (that.isSetCols()) {
                // 监听表格内操作列事件
                table.on(`tool(yunj_table_${id})`, function (obj) {
                    let el = $(this);
                    let args = el.data('args');
                    let rowData = obj.data;
                    let rowId = rowData.id;
                    let openPageTitle = args.title + " ID:" + rowId;
                    switch (obj.event) {
                        case 'openPopup':
                            let popupUrl = yunj.urlPushParam(args.url, {
                                id: rowId,
                                rawTable: that.id,
                            });
                            yunj.openPopup(popupUrl, openPageTitle, true);
                            break;
                        case 'openTab':
                            let tabUrl = yunj.urlPushParam(args.url, {
                                id: rowId,
                                rawTable: that.id,
                            });
                            yunj.openTab(tabUrl, openPageTitle, true);
                            break;
                        case 'asyncEvent':
                            args.ids = [rowId];
                            that.asyncEventRequest(args, that);
                            break;
                    }
                });
                // 监听表头排序事件
                table.on(`sort(yunj_table_${id})`, function (obj) {
                    that.fieldSort = ['asc', 'desc'].indexOf(obj.type) === -1 ? {} : {[obj.field]: obj.type};
                    that.reloadTableHandle(false);
                });
            }
        }

        // 切换状态选项卡
        async stateTabChange() {
            let that = this;
            that.renderState();
            await that.renderFilter();
            await that.renderTableHandle();
            return 'done';
        }

        // 表格异步事件请求
        asyncEventRequest(param) {
            let that = this;
            param = yunj.objSupp(param, {title: '操作请求', confirmText: null, event: '', url: '', ids: []});
            if (!yunj.isArray(param.ids) || yunj.isEmptyArray(param.ids)) {
                yunj.msg('请勾选要操作的数据列');
                return false;
            }
            let filter = {event: param.event, ids: param.ids};
            let requestData = {builderId: that.id, builderAsyncType: 'event', filter: filter};

            let eventRequest = () => {
                yunj.request((param.url ? param.url : that.url), requestData, "post").then(res => {
                    let requestData = requestData.filter;
                    let event = requestData.event;
                    if (yunj.isObj(res.data) && res.data.hasOwnProperty('reload') && !res.data.reload) {
                        that.asyncEventRequestDone(event, requestData, res);
                        return;
                    }
                    that.renderTable().then();
                    that.asyncEventRequestDone(event, requestData, res);
                }).catch(e => {
                    yunj.error(`${param.title}失败`);
                });
            };

            if (param.confirmText)
                yunj.confirm(param.confirmText, function () {
                    eventRequest();
                });
            else
                eventRequest();

        }

        // 异步事件请求完成
        asyncEventRequestDone(event, requestData, responseRes) {
            let that = this;
            $(doc).trigger(`yunj_table_${that.id}_event_done`, [event, requestData, responseRes]);
            $(doc).trigger(`yunj_table_${that.id}_event_${event}_done`, [requestData, responseRes]);
        }

        // 生成筛选表单对象id
        generateFilterFormId(state = false) {
            return this.id + (state !== false ? `_${state}` : "");
        }

        // 获取当前筛选表单对象id
        getCurrFilterFormId() {
            return this.id + (this.isSetState() ? `_${this.state}` : "");
        }

        // 生成筛选表单lay-filter，根据传入formId
        generateFilterFormLayFilterByFormId(formId){
            return formId + "_form";
        }

        // 生成筛选表单lay-filter，根据传入state
        generateFilterFormLayFilterByState(state = false){
            return this.generateFilterFormLayFilterByFormId(this.generateFilterFormId(state));
        }



        // 获取当前筛选表单lay-filter
        getCurrFilterFormLayFilter() {
            return this.getCurrFilterFormId() + "_form";
        }

        /**
         * 请求筛选的条件
         * @param args
         * @returns {any}
         */
        requestFilter(args = {}) {
            let that = this;
            args = yunj.objSupp(args, {
                filter: true,        // 是否包含筛选表单的值
                ids: false,          // 是否包含当前选中ids
                convert: true,       // 是否转换为json字符串
                state: that.state,    // 指定状态下的筛选条件（默认当前状态）
            });
            let data = {};
            if (that.isSetState()) data.state = args.state;
            if (args.ids) data.ids = table.checkStatus(that.layuiTableId()).data.map(row => {
                return row.id
            });
            if (args.filter && that.filterFormEl) {
                let [filterValues] = yunj.formData(that.id + (args.state ? `_${args.state}` : ""), validate);
                data = Object.assign({}, data, filterValues);
            }
            return args.convert ? JSON.stringify(data) : data;
        }

        /**
         * 请求条件sort
         * @returns {string}
         */
        requestSort() {
            return JSON.stringify(this.fieldSort);
        }

        // layui正式的表格id
        layuiTableId() {
            return `yunj_table_${this.id}`;
        }

    }

    $(doc).ready(function () {
        win.yunj.table = {};

        let tableEls = $('table[type=yunj]');
        if (yunj.isUndefined(YUNJ_TABLE) || !yunj.isObj(YUNJ_TABLE) || tableEls.length <= 0) return;
        tableEls.each(function () {
            let id = $(this).attr('id');
            if (!YUNJ_TABLE.hasOwnProperty(id)) return true;
            let args = YUNJ_TABLE[id];
            win.yunj.table[id] = new YunjTable({
                id: id,
                elem: $(this),
                args: args
            });
        });
    });

});
